<template>
  <div ref="canvas" />
</template>

<script lang="ts" setup>
import * as THREE from 'three';
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import { ref, onMounted } from "vue";

// 画布
const canvas = ref<any>('');
// 场景
const scene = new THREE.Scene();
// 相机
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 1500);
camera.position.set(0.01, 0, 0);

// 创建球体
const geometry = new THREE.SphereGeometry(100, 80, 80);
// 反转x轴上的几何图形，使所有面都指向内侧
geometry.scale( - 1, 1, 1 );

// 加载纹理图片
const texture = new THREE.TextureLoader().load(new URL("@/assets/house.jpg", import.meta.url).href);
// 构建材质
const material = new THREE.MeshBasicMaterial({ map: texture });

// 创建 mesh
const mesh = new THREE.Mesh(geometry, material);
// 将 mesh 添加到场景重
scene.add(mesh);

// 渲染器
const renderer = new THREE.WebGLRenderer({
  antialias: true,
});
renderer.setClearColor(0xffffff);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);

// 相机控件
const orbitControl = new OrbitControls(camera, renderer.domElement);
// 修正方向
orbitControl.rotateSpeed = -0.25;
orbitControl.update();

const onWindowResize = () => {
  // 更新相机长宽比
  camera.aspect = window.innerWidth / window.innerHeight;
  // 更新摄像机投影矩阵。在任何参数被改变以后必须被调用。
  camera.updateProjectionMatrix();
  // 更新渲染器大小
  renderer.setSize( window.innerWidth, window.innerHeight );
};
window.addEventListener( 'resize', onWindowResize );

onMounted(() => {
  canvas.value.appendChild(renderer.domElement);
  render();
});

const render = () => {
  requestAnimationFrame(render);
  renderer.render(scene, camera);
}

</script>
